package com.hhc.service.impl;

import com.hhc.dto.OperationLogDTO;
import com.hhc.entity.OperationLogDO;
import com.hhc.query.OperationLogQuery;
import com.hhc.repository.OperationLogRepository;
import com.hhc.service.OperationLogService;
import java.time.LocalDateTime;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   操作日志Service实现类
 * </p>
 * @author pc
 */
@Slf4j
@Service
public class OperationLogServiceImpl implements OperationLogService {

    @Autowired
    private OperationLogRepository operationLogRepository;

    @Transactional
    @Override
    public OperationLogDTO createOperationLog(OperationLogDTO operationLogDTO) {
        OperationLogDO operationLogDO = new OperationLogDO();
        BeanUtils.copyProperties(operationLogDTO, operationLogDO);
        operationLogDO.setCreateTime(LocalDateTime.now());
        operationLogRepository.save(operationLogDO);
        BeanUtils.copyProperties(operationLogDO, operationLogDTO);
        return operationLogDTO;
    }

    @Override
    public Page<OperationLogDTO> getOperationLogList(OperationLogQuery query) {
        Pageable pageable = PageRequest.of(query.getPage() - 1, query.getSize());
        Page<OperationLogDO> operationLogDOPage = operationLogRepository.findAllByUserIdAndOperationTypeAndModuleNameAndCreateTimeBetween(
                query.getUserId(), query.getOperationType(), query.getModuleName(), query.getStartTime(), query.getEndTime(), pageable);
        return operationLogDOPage.map(this::convertToDTO);
    }

    @Transactional
    @Override
    public boolean deleteOperationLog(Long id) {
        Optional<OperationLogDO> optionalOperationLogDO = operationLogRepository.findById(id);
        if (optionalOperationLogDO.isPresent()) {
            operationLogRepository.deleteById(id);
            return true;
        }
        return false;
    }

    private OperationLogDTO convertToDTO(OperationLogDO operationLogDO) {
        OperationLogDTO operationLogDTO = new OperationLogDTO();
        BeanUtils.copyProperties(operationLogDO, operationLogDTO);
        return operationLogDTO;
    }
}